package com.fingard.dsp.bank.directbank.tzb01;

import net.sf.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/12/12.
 */
public class TZB01BatPayRec extends TZB01Base implements IBatPayRec {

    /**
     * 批量代付提交
     *
     * @param p_req1988
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        try{
            //拼接请求报文头
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            TZB01Header header=new TZB01Header();
            header.tr_code="300002";
            header.req_no = p_req1988.reqBatchNO;
            writeCommonHeader(xmlTextWriter,header);
            xmlTextWriter.writeEndElement();
            //拼接请求报文体
            XElement body = new XElement("body","");
            body.addChild(new XElement("batch_no",p_req1988.reqBatchNO));//批次号
            body.addChild(new XElement("pay_acno",p_req1988.ownAct));//付款账号
            body.addChild(new XElement("pay_cur_code",convertCurToBank(p_req1988.ownCur)));//付款币种
            body.addChild(new XElement("pay_acname",p_req1988.ownActName));//付款户名
            body.addChild(new XElement("as_flag","0"));//是否使用账簿号 0：不需要 1：需
            body.addChild(new XElement("as_acno",""));//账簿号
            body.addChild(new XElement("supply_item","0001"));//项目编号 0001代发工资
            body.addChild(new XElement("amt",p_req1988.totalAmt));//总交易金额
            body.addChild(new XElement("count",p_req1988.totalNum));//总笔数
            body.addChild(new XElement("purpose",""));//用途
            body.addChild(new XElement("postscript",p_req1988.useType));//附言
            //拼接批付数据到文件
            String fileName=p_req1988.reqBatchNO+".txt";
            String filePath=StringHelper.trimEnd(FGBiz.dspCenter.dspSet.dataDirPath, "/") + File.separator + p_req1988.reqHeader.bankCode
                    + File.separator + Format.Date8Format.format(new Date()).substring(0,6)+ File.separator + Format.Date8Format.format(new Date()).substring(7,8);
            if(!FileHelper.existFile(filePath)){
                FileHelper.mkdir(filePath);
            }
            int tmpCount=0;
            StringBuilder sb=new StringBuilder();
            while(p_req1988.readRecord()){
                tmpCount++;
                //账号|币种|户名|卡折标志（0-卡  1-折）|金额|附言|
                sb.append(p_req1988.readedDetail.recAct).append("|").append(convertCurToBank(p_req1988.readedDetail.recCur)).append("|")
                    .append(p_req1988.readedDetail.recName).append("|").append("").append("|")
                    .append(p_req1988.readedDetail.payAmount).append("|").append(p_req1988.readedDetail.askNumber).append("|");
                if(tmpCount!=Integer.parseInt(p_req1988.totalNum)){
                    sb.append("\r\n");
                }
            }
            String fileNamePath=filePath + File.separator + fileName;
            FileHelper.writeFile(fileNamePath,sb);
            //上传文件到前置机目录
            if(FileHelper.existFile(fileNamePath)){
                int result = SmbFileUtil.smbUploading(fileNamePath, "/", FGBiz.dspCenter.dspSet.receiptShareDir);
                if(result==-1){
                    retAts.respCode = "-1";
                    retAts.respInfo = "上传文件到前置机目录异常";
                    retAts.writeRetToATS();
                    return retAts;
                }
            }
            body.addChild(new XElement("file_name",fileName));//文件名
            body.addChild(new XElement("field_num","6"));//每条记录字段数
            if(tmpCount!=Integer.parseInt(p_req1988.totalNum)){
                retAts.respCode = "-1";
                retAts.respInfo = "写入数据异常";
                retAts.writeRetToATS();
                return retAts;
            }
            body.addChild(new XElement("record_num",p_req1988.totalNum));//文件内记录数
            xmlTextWriter.writeXElement(body);
            xmlTextWriter.writeEndDocument();
            //拼接报文头
            int length=xmlTextWriter.toXmlString().getBytes(getCharset()).length+2;
            String head=String.format("%-10s",length+"")+"00";
            //发送请求报文
            String[] bankResult = sendToBank(head+xmlTextWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader xmlSbReader = loadBankRespXmlReader(bankResult[1].substring(bankResult[1].indexOf("<ap>")), tmpSbMsg);
                if (xmlSbReader != null) {
                    String succFlag= xmlSbReader.getFirstText("/ap/head/succ_flag");
                    String respCode = xmlSbReader.getFirstText("/ap/head/ret_code");
                    String respInfo = xmlSbReader.getFirstText("/ap/head/ret_info");
                    retAts.respCode = "0";
                    retAts.respInfo = respInfo;
                    retAts.reqSeqID = p_req1988.reqBatchNO;
                    if("0".equals(succFlag)){//交易成功：处理中
                        retAts.transState = succFlag;
                    }else {
                        retAts.transState = respCode;//9999、1102结果未知
                    }
                    retAts.payInfoCode = retAts.transState;
                }else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            }else if(bankResult[0].equals(ConnState.FAIL)){
                retAts.respCode = "0";
                retAts.respInfo = bankResult[1];
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = bankResult[0];
            }
            else{
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        }catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            WriteBankLogLn("批量代发异常："+e);
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1988.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        // 返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        try {
            //拼接请求报文头
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            TZB01Header header=new TZB01Header();
            header.tr_code="200201";
            header.req_no = p_req1998.reqBatchNO;
            writeCommonHeader(xmlTextWriter,header);
            xmlTextWriter.writeEndElement();
            //拼接请求报文体
            XElement body = new XElement("body","");
            body.addChild(new XElement("batch_no",p_req1998.reqBatchNO));//批次号
            body.addChild(new XElement("serial_no",""));//平台流水号
            body.addChild(new XElement("cms_corp_no",""));//客户号
            body.addChild(new XElement("tr_acdt",p_req1998.bgnDate));//交易日期
            xmlTextWriter.writeXElement(body);
            xmlTextWriter.writeEndDocument();
            //拼接报文头
            int length=xmlTextWriter.toXmlString().getBytes(getCharset()).length+2;
            String head=String.format("%-10s",length+"")+"00";
            //发送请求报文
            String[] bankResult = sendToBank(head+xmlTextWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader xmlSbReader = loadBankRespXmlReader(bankResult[1].substring(bankResult[1].indexOf("<ap>")), tmpSbMsg);
                if (xmlSbReader != null) {
                    String succFlag= xmlSbReader.getFirstText("/ap/head/succ_flag");
                    String respCode = xmlSbReader.getFirstText("/ap/head/ret_code");
                    String respInfo = xmlSbReader.getFirstText("/ap/head/ret_info");
                    if ("0".equals(succFlag) && "0000".equals(respCode)) {//交易成功
                        String totalNum=xmlSbReader.getFirstText("/ap/body/recorde_num");//总数
                        String valueNum=xmlSbReader.getFirstText("/ap/body/field_num");//字段数
                        String serial_recode=xmlSbReader.getFirstText("/ap/body/serial_recode");//字段域
                        if(!"0".equals(totalNum) && !"0".equals(valueNum) && !com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper.isNullOrEmpty(serial_recode)){
                            retAts.respCode = "0";
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.writeBeforeDetail();
                            //0、明细序列号|1、收款账号|2、币种(01-人民币)|3、收款户名|4、借贷标志(D-借,C-贷)|
                            //5、附言|6、交易日期|7、交易时间|8、交易状态(6-失败,9-成功)|9、错误信息|10、批次号|
                            String[] content=serial_recode.split("\\|");
                            if(content.length==Integer.parseInt(new BigDecimal(totalNum).multiply(new BigDecimal(valueNum)).toString())){
                                for(int i=0;i<Integer.parseInt(totalNum);i++){
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.payAct = p_req1998.ownAct;
                                    tmpRetDetail.payName = "";
                                    tmpRetDetail.recName = content[3+i*Integer.parseInt(valueNum)].trim();
                                    tmpRetDetail.recAct =content[1+i*Integer.parseInt(valueNum)].trim();
                                    tmpRetDetail.payAmount = "";
                                    tmpRetDetail.curType = convertCurToATS(content[2+i*Integer.parseInt(valueNum)].trim());
                                    tmpRetDetail.result = content[8+i*Integer.parseInt(valueNum)].trim();
                                    tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                    tmpRetDetail.postScript = content[5+i*Integer.parseInt(valueNum)].trim();//批内流水号
                                    tmpRetDetail.usage =content[5+i*Integer.parseInt(valueNum)].trim();
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }else {
                                retAts.respCode ="-1";
                                retAts.respInfo = "返回数据异常";
                            }
                        }else {
                            retAts.respCode ="-1";
                            retAts.respInfo = "返回记录为0";
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = respInfo;
                    }
                }else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            }else {
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        if ("-1".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
